/*
 * @Author: fhw
 * @Date: 2022-07-17 15:17:05
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2023-02-20 11:49:33
 * @Description:
 */
import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { Request, Response } from 'express';
import { equals } from 'ramda';
import { Logger } from './log4js/utils';
@Catch(HttpException)
export class HttpExceptionFilter implements ExceptionFilter {
  catch(exception: HttpException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();
    const exceptionRes: any = exception.getResponse();
    const { message } = exceptionRes;
    const errorResponse = {
      data: null, // 获取全部的错误信息
      msg: message,
      code: '400', // 自定义code
      url: request.originalUrl, // 错误的url地址
      success: false,
    };
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;
    if (equals(status, 401) && equals(message, 'Unauthorized')) {
      errorResponse.msg = '获取token失败';
      errorResponse.code = '401';
    }
    if (equals(status, 403) && equals(message, 'Forbidden resource')) {
      errorResponse.msg = '权限不足，请联系管理员配置权限';
      errorResponse.code = '403';
    }
    const logFormat = ` <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    Request original url: ${request.originalUrl}
    Method: ${request.method}
    IP: ${request.ip}
    Status code: ${errorResponse.code}
    Parmas: ${JSON.stringify(request.params)}
    Query: ${JSON.stringify(request.query)}
    Body: ${JSON.stringify(request.body)}
    Msg: ${errorResponse.msg}
    Response: ${exception.toString()} \n  <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
    `;
    // Logger.info(logFormat);
    response.status(200);
    response.header('Content-Type', 'application/json; charset=utf-8');
    response.send(errorResponse);
    // response.status(status).json({
    //   status,
    //   timestamp: new Date().toISOString(),
    //   path: request.url,
    //   error,
    //   message,
    //   success,
    // });
  }
}
